package com.ls.lserp.modules.order.service;


import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.service.CrudService;
import com.ls.lserp.common.utils.CacheUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.modules.common.entity.UploadFile;
import com.ls.lserp.modules.order.dao.AuditInfoDao;
import com.ls.lserp.modules.order.dao.BigcargoStyleDao;
import com.ls.lserp.modules.order.dao.SpecimenProductionDao;
import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.order.entity.BigcargoStyle;
import com.ls.lserp.modules.order.entity.SpecimenProduction;
import com.ls.lserp.modules.setting.dao.CompanyUserDao;
import com.ls.lserp.modules.setting.entity.CompanyUser;
import com.ls.lserp.modules.sys.dao.UploadFileDao;
import com.ls.lserp.modules.sys.dao.UserDao;
import com.ls.lserp.modules.sys.entity.User;
import com.ls.lserp.modules.sys.utils.UserUtils;

/**
 * @ClassName: SpecimenProductionService
 * @Description: 样品生产 一览 新建 删除 修改
 * 
 * @author 
 * @date 2017年02月10日
 *
 */

@Service
@Transactional(readOnly = true)
public class SpecimenProductionService extends CrudService<SpecimenProductionDao, SpecimenProduction> {
	// 分类方法接口
	@Autowired
	private SpecimenProductionDao specimenProductionDao;
	
    @Autowired
    private UserDao userDao;
    
    //大货款式
    @Autowired
    private BigcargoStyleDao bigcargoStyleDao;
    
    //上传文件
    @Autowired
    private UploadFileDao uploadFileDao;
    
    // 公司人员
    @Autowired
    private CompanyUserDao  companyUserDao;
    
    // 审核表
    @Autowired
    private AuditInfoDao  auditInfoDao;
    
	/**
	 * @Title: findList
	 * @Description: 一览查询
	 * @param page
	 * @param specimenProduction
	 * @return Page<specimenDemand>
	 */
	public Page<SpecimenProduction> findList(Page<SpecimenProduction> page, SpecimenProduction specimenProduction) {
		
		// tab页分，检索条件设定(0:全部,1:待打版,2:待打样,3:待验收,4:完了)
		int tabFlg = specimenProduction.getTabPageStatus();
		if(1==tabFlg){
			specimenProduction.setSampleProductionStatus(ResourcesUtil.getConfig("specimen_production_status_wait_template"));
		}else if(2==tabFlg){
			specimenProduction.setSampleProductionStatus(ResourcesUtil.getConfig("specimen_production_status_wait_sample"));
		}else if(3==tabFlg){
			specimenProduction.setSampleProductionStatus(ResourcesUtil.getConfig("specimen_production_status_wait_accept"));
		}else if(4==tabFlg){
			specimenProduction.setSampleProductionStatus(ResourcesUtil.getConfig("specimen_production_status_done"));
		}else{
			specimenProduction.setSampleProductionStatus("");
		}
		
		// 阶段(样品)
		String auditPhaseCdSample = ResourcesUtil.getConfig("audit_phase_specimen");
		
		// 设置分页参数
		specimenProduction.setPage(page);
		specimenProduction.setAuditPhaseCd(auditPhaseCdSample);
		// 取得查询数据
		List<SpecimenProduction> updateList = specimenProductionDao.findList(specimenProduction);
		
		BigDecimal sampleCost = null;
		SpecimenProduction audit = null;
		SpecimenProduction resultAudit = null;
		
		for (SpecimenProduction sp : updateList) {
			
			// 设定成本价格
			sampleCost = new BigDecimal("0");
			sampleCost = sampleCost.add(checkBigDecimalNull(sp.getSampleMaterialCost()));
			sampleCost = sampleCost.add(checkBigDecimalNull(sp.getSampleMandayCost()));
			sampleCost = sampleCost.add(checkBigDecimalNull(sp.getSampleOtherCost()));
			sp.setSampleCost(sampleCost);
			
			// 设定申核完了日
			audit = new SpecimenProduction();
			audit.setId(sp.getId());
			audit.setAuditPhaseCd(auditPhaseCdSample);
			resultAudit = specimenProductionDao.getAuditInfo(audit);
			if(resultAudit!=null){
				sp.setSampleaAtualDueDate(resultAudit.getSampleaAtualDueDate());
			}
			
			// 设定打版人员名
			sp.setTemplateUserName(getUserAllName(sp.getMakeId()));
			
			// 设定打样人员名
			sp.setSampleUserName(getUserAllName(sp.getSamId()));
		}
		
		// 执行分页查询
		page.setList(updateList);
		return page;
	}
	
	/**
	 * 根据ID获取用户
	 * @param id
	 * @return 取不到返回null
	 */
	public String getUserAllName(long id){
		if(id==0){
			return "";
		}
		User user = (User)CacheUtils.get(UserUtils.USER_CACHE, UserUtils.USER_CACHE_ID_ + id);
		if (user ==  null){
			user = userDao.get(id);
			if (user == null){
				return "";
			}
		}
		return user.getFirstName()+user.getLastName();
	}
	
	/**
	 * 获取单条数据
	 * @param id
	 * @return
	 */
	public SpecimenProduction getSample(Long id) {
		SpecimenProduction resultProduction = specimenProductionDao.get(id);
		if(resultProduction==null){
			return null;
		}
		
		// 取得所有物料价格
		SpecimenProduction paramMaterialCost = new SpecimenProduction();
		paramMaterialCost.setSampleId(resultProduction.getSampleId());
		List<SpecimenProduction> resultMaterialCostList = specimenProductionDao.findMaterialCostList(paramMaterialCost);
		
		BigDecimal totalCost = new BigDecimal("0");
		for(SpecimenProduction resultMaterialCost : resultMaterialCostList){
			totalCost = totalCost.add(
					(checkBigDecimalNull(resultMaterialCost.getMaterialLoss()).multiply(checkBigDecimalNull(resultMaterialCost.getMaterialUnitPrice()))).setScale(2, BigDecimal.ROUND_HALF_UP));
		}
		resultProduction.setSampleMaterialCost(totalCost);
		
		resultProduction.setSampleMandayCost(checkBigDecimalNull(resultProduction.getSampleMandayCost()));
		resultProduction.setSampleOtherCost(checkBigDecimalNull(resultProduction.getSampleOtherCost()));
		resultProduction.setSampleCost(checkBigDecimalNull(resultProduction.getSampleMaterialCost()).add(checkBigDecimalNull(resultProduction.getSampleMandayCost())).add(checkBigDecimalNull(resultProduction.getSampleOtherCost())));
		resultProduction.setSampleUserName(getUserAllName(resultProduction.getSamId()));
		resultProduction.setTemplateUserName(getUserAllName(resultProduction.getMakeId()));

		CompanyUser companyUser = new CompanyUser();
		// 取得所有打版人员信息
		companyUser.setDutyId(StringUtils.toLong(ResourcesUtil.getConfig("duty_id_template")));
		resultProduction.setTemplateUserList(companyUserDao.findList(companyUser));
		
	    // 取得所有打样人员信息
		companyUser.setDutyId(StringUtils.toLong(ResourcesUtil.getConfig("duty_id_sample")));
		resultProduction.setSampleUserList(companyUserDao.findList(companyUser));
		
		return resultProduction;
	}
	
	/**
	 * 
	 * @param companyUser
	 * @return
	 */
	public List<CompanyUser> findSampleUserList(CompanyUser companyUser){
		return companyUserDao.findList(companyUser);
	}
	
	/**
	 * check BigDecimal
	 * @param cost
	 * @return 取不到返回0
	 */
	public BigDecimal checkBigDecimalNull(BigDecimal cost){
		if(cost==null){
			return new BigDecimal("0");
		}
		return cost;
	}
	
	/**
	  * @Title: saveFile
	  * @Description: 保存图片信息
	  * @param @param specimenProduction
	  * @return void 
	  * @throws Exception
	  */
	@Transactional(readOnly = false)
	public void saveFile(SpecimenProduction specimenProduction) throws Exception{
		if (specimenProduction.getUploadFileEntity() != null) {
			//图片集
			List<UploadFile> uploadFileList = specimenProduction.getUploadFileEntity().getUploadFileList();
			if (uploadFileList != null && uploadFileList.size() > 0) {
				BigcargoStyle bigcargoStyle = new BigcargoStyle();
				long styleId = specimenProductionDao.getStyleIDBySizeID(specimenProduction);
				bigcargoStyle.setStyleID(styleId);
				for (UploadFile uFile : uploadFileList) {
					uFile.preInsert();
					//插入文件表
					uFile.setFileSource(1L);
					uploadFileDao.saveUploadFile(uFile);
					//插入样品生产和上传文件关联表
					specimenProductionDao.insertSampleSizeFile(specimenProduction.getId(),uFile.getFileId());
					//插入款式_上传文件关联表
					bigcargoStyle.setFileID(uFile.getFileId());
					bigcargoStyleDao.insertStyleFile(bigcargoStyle);
				}
			}
		}
	}
	
	/**
	  * @Title: saveDict
	  * @Description: 保存基准数据
	  * @param @param dict
	  * @return void 
	  * @throws
	  */
	@Transactional(readOnly = false)
	public void saveSpecimenProduction(SpecimenProduction specimenProduction) {
		
		// 样品需求单状态
		String requestStatus = specimenProduction.getSampleRequestStatus();
		// 样品生产状态
		String productionStatus = specimenProduction.getSampleProductionStatus();
		
		if(productionStatus.equals(ResourcesUtil.getConfig("specimen_production_status_wait_template")) && specimenProduction.getOldSamId()==0){
			specimenProduction.setSamId(0L);
		}
		
		// 打版完成日入力，需求单状态更新"新建"->"生产中",样品生产状态更新"待打版"->"待打样"
		if(productionStatus.equals(ResourcesUtil.getConfig("specimen_production_status_wait_template")) && specimenProduction.getTemplateEndDate()!=null&& specimenProduction.getSampleEndDate()==null){
			specimenProduction.setSampleProductionStatus(ResourcesUtil.getConfig("specimen_production_status_wait_sample"));
			if(requestStatus.equals(ResourcesUtil.getConfig("specimen_demand_status_create"))){
				specimenProduction.setSampleRequestStatus(ResourcesUtil.getConfig("specimen_demand_status_production"));
			}
		}else if (specimenProduction.getSampleEndDate()!=null) {
			specimenProduction.setSampleProductionStatus(ResourcesUtil.getConfig("specimen_production_status_wait_accept"));
			if(requestStatus.equals(ResourcesUtil.getConfig("specimen_demand_status_create"))){
				specimenProduction.setSampleRequestStatus(ResourcesUtil.getConfig("specimen_demand_status_production"));
			}
		}
		
		// 更新样品尺寸表数据
		specimenProduction.preUpdate();
		specimenProductionDao.update(specimenProduction);
		
		// 更新样品管理表
		specimenProductionDao.updateSampleRemark(specimenProduction);
	}
	
    /**
     * @Title: findAuditList
     * @Description: 查询所有履历
     * @param @param auditInfo
     * @param @return
     * @return List<AuditInfo> 
     * @throws
     */
   public AuditInfo findAuditInfo(AuditInfo auditInfo) {
	   AuditInfo audit = new AuditInfo();
	   audit.setAuditList(auditInfoDao.findAllList(auditInfo));
	   audit.setAuditStatus(auditInfoDao.findAuditAcceptCount(auditInfo));
       // 执行查询
       return audit;
   }
   
	/**
	  * @Title: saveAudit
	  * @Description: 保存履历信息
	  * @param @param auditInfo
	  * @return void 
	  * @throws
	  */
	@Transactional(readOnly = false)
	public void saveAuditInfo(AuditInfo auditInfo,boolean isUpdateStatus) {
		
		 // 插入履历表
	     auditInfo.preInsert();
	     auditInfo.setAuditDate(new Date());
	     auditInfo.setAuditUserId(UserUtils.getUser().getId());
         // 新建版本号赋值1
	     auditInfo.setVersion(1L);
	     auditInfoDao.insert(auditInfo);
	     
	     // 修正样品生产状态
	     auditInfo.preUpdate();
	     specimenProductionDao.updateProductionStatus(auditInfo);
	     
	     // 修正样品需求单状态
	     if(isUpdateStatus){
	     specimenProductionDao.updateSampleRequestStatus(auditInfo);	 
	     }
	}
	
    /**
     * @Title: isSampleProductionDone
     * @Description: 判断样品生产是否全部完了
     * @param @param productionId
     * @param @return
     * @return true全部完了
     * @throws
     */
   
   public Boolean isSampleProductionDone(long sampleId,long productionId) {
	   
	   boolean auditResult = true;
	   
	   // 查询所有样品的审核已通过的结果
	   AuditInfo ai = new AuditInfo();
	   ai.setAuditRelateId(sampleId);
	   ai.setAuditPhaseCd(ResourcesUtil.getConfig("audit_phase_specimen"));
	   List<AuditInfo> auditInfoList = specimenProductionDao.findSampleAuditResultList(ai);
	   
	   if(auditInfoList==null){
		   return false;
	   }
	   
	   for(AuditInfo auditInfo : auditInfoList){
		   
		   // 样品所有审核结果没有通过
		   if(auditInfo.getAuditResult() == 0 && auditInfo.getAuditRelateId()!=productionId){
			   auditResult = false;
			   break;
		   }
	   }
	   
       return auditResult;
   }
   
   /**
    * @Title: getAuditResult
    * @Description: 审核结果
    * @param @param auditInfo
    * @param @return
    * @return 审核结果通过数
    * @throws
    */
  
  public long getAuditResult(AuditInfo auditInfo) {
	   
      return auditInfoDao.findAuditAcceptCount(auditInfo);
  }
}
